package cn.cai.service.impl;


import cn.cai.pojo.Parameter;
import cn.cai.pojo.QueryData;
import cn.cai.pojo.ResponseData;
import cn.cai.service.ReportPeace;
import cn.cai.utils.Base64Util;
import cn.cai.utils.URLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

@Service
public class ReportPeaceImpl implements ReportPeace {


    /**
     * 报平安逻辑实现
     * @param parameter post请求中的url类型的参数
     * @return 请求的结果
     */
    @Override
    public ResponseData sendParamForPost(Parameter parameter) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        ResponseData responseData = null;
        // http://xg.sqxy.edu.cn/xgh5/openData?command=XGXT&param=%7B%22cmd%22%3A%22yqsbFormSave%22%2C%22xh%22%3A%221911014001%22%2C%22sbsj%22%3A%222021-08-14%22%2C%22nl%22%3A%2220%22%2C%22lxfs%22%3A%2215660917807%22%2C%22jzdq%22%3A%22410221%22%2C%22jzdq_xxdz%22%3A%22%E5%95%86%E4%B8%98%E5%AD%A6%E9%99%A2%22%2C%22tw%22%3A%2236.5%22%2C%22sflx%22%3A%220%22%2C%22jcbr%22%3A%220%22%2C%22zyzz%22%3A%221%2C%22%2C%22fbrq%22%3A%22%22%2C%22zyzzms%22%3A%22%22%2C%22bz%22%3A%22%22%2C%22bz1%22%3A%22%22%2C%22wcjtgj%22%3A%22%22%2C%22wcjtgjxq%22%3A%22%22%2C%22wcdq%22%3A%22%22%2C%22wcdqxxdz%22%3A%22%22%2C%22lkdate%22%3A%22%22%2C%22fhdate%22%3A%22%22%2C%22zszt%22%3A%22%22%7D"
//        String str = basicInformation.toString();
        String str = JSON.toJSONString(parameter);
        String result = URLUtil.coding(str);
        HttpPost httpPost = new HttpPost("http://xg.sqxy.edu.cn/xgh5/openData?command=XGXT&param=" + result);
        CloseableHttpResponse response = null;
        response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        // 判断响应状态
        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == 200){
            // 请求成功,将请求的内容返回
            responseData = JSON.parseObject(EntityUtils.toString(entity), ResponseData.class);

        }
        // 关闭IO
        response.close();
        httpClient.close();
        return responseData;

    }

    /**
     * 通过get获取报平安数据
     * @param xh 学号
     * @return List<QueryData>
     */
    @Override
    public List<QueryData> queryDataForGet(String xh) {
        List<QueryData> list = null;
        // 固定参数 http://xg.sqxy.edu.cn//xgh5/openData?command=XGXT&param=
        // URL编码：%7B%22cmd%22%3A%22xsyqsbApplyViewList%22%2C%22xh%22%3A%22MTkxMTAxNDAwMQ%3D%3D%22%2C%22rqyf%22%3A%22%22%7D
        // http://xg.sqxy.edu.cn//xgh5/openData?command=XGXT&param=%7B%22cmd%22%3A%22xsyqsbApplyViewList%22%2C%22xhMTkxMTAxNDAwMQ%3D%3Drqyf%22%3A%22%22%7D
        StringBuilder url = new StringBuilder("http://xg.sqxy.edu.cn//xgh5/openData?command=XGXT&param=%7B%22cmd%22%3A%22xsyqsbApplyViewList%22%2C%22xh%22%3A%22");
        // 对传入的学号先进行Base64编码在进行URL编码
        //URLUtil.coding(Base64Util.encode(xh.getBytes(StandardCharsets.UTF_8)))
        url.append(URLUtil.coding(Base64Util.encode(xh.getBytes(StandardCharsets.UTF_8))));
        url.append("%22%2C%22rqyf%22%3A%22%22%7D");
        // 获取Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Get请求
        HttpGet httpGet = new HttpGet(url.toString());
        // 响应模型
        CloseableHttpResponse response = null;
        RequestConfig requestConfig = RequestConfig.custom()
                // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(10000)
                // 设置请求超时时间（单位毫秒）
                .setConnectionRequestTimeout(10000)
                // socket读写超时时间(单位毫秒)
                .setSocketTimeout(10000)
                // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(true)
                .build();
        // 将上面的配置信息，运用到这个Get请求
        httpGet.setConfig(requestConfig);
        // 由客户端执行（发送）Get请求
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200){
                // 从响应模型中获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null){
                    // 提取响应数据
                    JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity));
                    JSONArray data = jsonObject.getJSONArray("data");
                    list = data.toJavaList(QueryData.class);
                    return list;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
